package com.example.forum.interceptor;

import com.example.forum.config.ContentConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    //设置默认的返回的URL路径
    @Value("${bit-forum.login.url}")
    private String defaultUrl;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session中拿到信息
        HttpSession session = request.getSession(false);

        if(session != null && session.getAttribute(ContentConfig.USER_SESSION) != null){
            //说明这里的用户已经进行了登录的操作
            return true;
        }
        //更改路径格式
        if(!defaultUrl.startsWith("/")){
            defaultUrl = "/"+ defaultUrl;
        }

        //由于没有进行登录，就跳转到我们的登录页面

        response.sendRedirect(defaultUrl);

        return false;
    }
}
